import { useIntl } from '@umijs/max';
import * as echarts from 'echarts';
import ReactECharts from 'echarts-for-react';
import React from 'react';
import { fitChartSize } from '../utils/tools';

export interface StationIncomeData {
  date: string;
  income: number | string | null;
}

interface StationDailyIncomeProps {
  data: StationIncomeData[];
  dataType: string; // 新增的参数
}

// 自定义函数来调整 Y 轴的最大值和最小值
const adjustYAxisValues = (max: number, min: number) => {
  const defaultMax = 10; // 默认最大值
  const defaultMin = 0; // 默认最小值
  const finalMax = max > 0 ? Math.ceil(max / 10) * 10 : defaultMax;
  const finalMin = min < 0 ? Math.floor(min / 10) * 10 : defaultMin;

  // 计算刻度间隔
  const range = finalMax - finalMin;
  const interval = Math.ceil(range / 5);

  return {
    max: finalMax,
    min: finalMin,
    interval,
  };
};

const StationDailyIncome: React.FC<StationDailyIncomeProps> = ({ data, dataType }) => {
  // 处理数据，将 null 和 '--' 统一设置为 0
  const processedData = data.map((item) => ({
    ...item,
    income: item.income === null || item.income === '--' ? 0 : item.income,
  }));
  const intl = useIntl();

  // 提取数据并格式化日期
  const dates = processedData.map((item) => {
    const [year, month, day] = item.date.split('-');
    if (dataType === 'year') {
      return year; // 年度显示年份
    } else if (dataType === 'month') {
      return `${year.slice(2)}/${month}`; // 月度显示 年/月
    } else {
      return `${month}/${day}`; // 日期显示 月/日
    }
  });

  const incomes = processedData.map((item) => item.income as number); // 处理后的数据不包含 null 或 '--'

  // 计算Y轴的最大值和最小值
  const maxIncome = Math.max(...incomes);
  const minIncome = Math.min(...incomes);

  // 调整 Y 轴的最大值和最小值
  const { max: yAxisMax, min: yAxisMin } = adjustYAxisValues(maxIncome, minIncome);

  const option = {
    backgroundColor: 'transparent',
    title: {
      text: '单位：(万元)',
      textStyle: {
        color: 'rgba(131, 162, 192, 1)',
        fontSize: fitChartSize(12),
      },
      top: '4%',
      left: '2%',
      show: false,
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(3, 25, 54, 0.7)', // 设置背景颜色和透明度
      borderColor: '#4c8fce', // 设置边框颜色
      borderWidth: 1, // 设置边框宽度
      textStyle: {
        color: '#C4D4F1', // 设置文字颜色
        fontSize: fitChartSize(12),
      },
      formatter: (params: any) => {
        const date = new Date(data[params[0].dataIndex].date);
        let formattedDate = '';
        if (dataType === 'year') {
          formattedDate = `${date.getFullYear()}`;
        } else if (dataType === 'monthS') {
          formattedDate = `${date.getFullYear()}-${date.getMonth() + 1}`;
        } else {
          formattedDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
        }
        const income = params[0].data.toFixed(2);
        return `${formattedDate}<br/>${intl.formatMessage({ id: 'bigdata.revenue' })}: ${
          income === '0.00' ? '--' : income
        } ${intl.formatMessage({ id: 'bigdata.wy' })}`;
      },
    },
    grid: {
      left: '3%',
      right: '5%',
      bottom: '6%',
      top: '5%',
      containLabel: true,
    },
    xAxis: {
      data: dates,
      type: 'category',
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#50637A',
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        textStyle: {
          color: '#77a5f1',
          fontSize: fitChartSize(12),
          padding: [0, 0, 0, 0],
          interval: 0, // 确保显示所有标签
          align: 'center', // 确保标签居中对齐
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#77a5f1',
        fontSize: fitChartSize(12),
        padding: [0, 10, 0, 0],
        formatter: function (value: number) {
          return Math.round(value); // 取整
        },
      },
      splitLine: {
        lineStyle: {
          type: 'dotted', // 设置为虚线
          color: 'rgba(53, 78, 114, 0.3)', // 颜色可根据需要调整
        },
      },
      min: yAxisMin,
      max: yAxisMax,
      // interval: yAxisInterval, // 动态设置刻度间隔
    },
    series: [
      {
        type: 'line',
        data: incomes,
        smooth: true,
        color: '#508fff',
        lineStyle: {
          width: 2,
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(
            0,
            0,
            0,
            1,
            [
              { offset: 0, color: '#13c5ff' },
              { offset: 1, color: '#508fff' },
            ],
            false,
          ),
        },
        symbol: 'circle',
        symbolSize: 6,
      },
    ],
  };

  return <ReactECharts option={option} style={{ width: '100%', height: fitChartSize(150) }} />;
};

export default StationDailyIncome;
